package com.dodock.android.banglapapers.ui;

import java.util.Vector;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dodock.android.banglapapers.BanglaNews;
import com.dodock.android.banglapapers.ComplexScriptHelper;
import com.dodock.android.banglapapers.InternetConnectivity;
import com.dodock.android.banglapapers.MyApplication;
import com.dodock.android.banglapapers.NewsDetails;
import com.dodock.android.banglapapers.NewsList;
import com.dodock.android.banglapapers.R;
import com.dodock.android.banglapapers.WebServerOperation;
import com.google.analytics.tracking.android.GoogleAnalytics;
import com.google.analytics.tracking.android.Tracker;
import com.loopj.android.image.SmartImageView;

public class NewsDetailsActivity extends BaseActivity {

	private ProgressDialog progressDialog;
	private boolean bError = false;
	private String newsId = "";
	private String newsPaperId = "";
	public static NewsDetails newsDetails;
	private int newsNo = 0;
	private String language = "";
	private Typeface fontBN;
	private Typeface fontEN;
	private String parent = "";
	private Vector<NewsList> newsList;
	Button saveNewsBtn;
	Vector<NewsDetails> newsDetailsVector;
	Button prevButton;
	Button nextNewsBtn;
	
	private Tracker mGaTracker;
	private GoogleAnalytics mGaInstance;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
				
		//Google Analytics
		try{
		    mGaInstance = GoogleAnalytics.getInstance(this);
		    mGaTracker = mGaInstance.getTracker(getResources().getString(R.string.ga_trackingId));
		}
		catch (Exception e) {
		}
		//--Google Analytics
		
		
		setContentView(R.layout.news_details);
		newsId = getIntent().getExtras().getString("newsId");
		newsPaperId = getIntent().getExtras().getString("newsPaperId");
		newsNo = getIntent().getExtras().getInt("newsNo");
		parent = getIntent().getExtras().getString("parent");
		language = getIntent().getExtras().getString("language");
		fontBN = Typeface.createFromAsset(this.getAssets(),
				"font/SutonnyMJ.ttf");
		fontEN = Typeface.DEFAULT;
		if (parent.equalsIgnoreCase("TopNews"))
			newsList = TopNewsActivity.newsList;
		else if (parent.equalsIgnoreCase("NewsList"))
			newsList = NewsListActivity.newsList;
		else if (parent.equalsIgnoreCase("SavedNews")) {
			newsDetailsVector = SavedNewsActivity.newsList;
			for (int i = 0; i < newsDetailsVector.size(); i++) {
				if (newsDetailsVector.get(i).getPaperId()
						.equalsIgnoreCase(newsPaperId)
						&& newsDetailsVector.get(i).getId()
								.equalsIgnoreCase(newsId)) {
					newsNo = i;
					newsDetails = newsDetailsVector.elementAt(newsNo);
					newsPaperId = newsDetails.getPaperId();
					language = newsDetails.getLanguage();
					break;
				}
			}
		}

		prevButton = (Button) findViewById(R.id.prevBtn);
		prevButton.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if (newsNo > 0) {
					newsNo--;
					newNewsDetails();
				}
			}
		});

		ImageView facebookBtn = (ImageView) findViewById(R.id.facebookBtn);
		facebookBtn.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				try {
					Intent facebookIntent = new Intent(Intent.ACTION_SEND);
					facebookIntent.setType("text/plain");
					facebookIntent.putExtra(Intent.EXTRA_SUBJECT,
							"Shared from BanglaPapers");
					facebookIntent.putExtra(Intent.EXTRA_TEXT,
							newsDetails.getSharelink());
					startActivity(Intent.createChooser(facebookIntent,
							"Check out the news"));
				} catch (Exception ex) {
					Toast.makeText(NewsDetailsActivity.this,
							"Application not found", Toast.LENGTH_SHORT).show();
				}
			}
		});

		saveNewsBtn = (Button) findViewById(R.id.saveNewsBtn);
		boolean isSaved = false;
		try{
			isSaved = BanglaNews.getDatabaseManager().isNewsSaved(
				newsPaperId + newsId);
		}
		catch(Exception ex){
			
		}
		if (isSaved) {
			saveNewsBtn.setText("Unsave");
		} else {
			saveNewsBtn.setText("Save News");
		}

		saveNewsBtn.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				try{
					boolean isSaved = BanglaNews.getDatabaseManager().isNewsSaved(
							newsPaperId + newsId);
					if (isSaved) {
						saveNewsBtn.setText("Save News");
						BanglaNews.getDatabaseManager().deleteSavedNews(
								newsPaperId + newsId);
					} else {
						String title;
						String details;
						if (language.equals("bn")) {
							title = ComplexScriptHelper.UnicodeToAnsi(newsDetails
									.getTitle());
							details = ComplexScriptHelper.UnicodeToAnsi(newsDetails
									.getDetailsNews());
						} else {
							title = newsDetails.getTitle();
							details = newsDetails.getDetailsNews();
						}
						saveNewsBtn.setText("Unsave");
						BanglaNews.getDatabaseManager().addNewsDB(newsPaperId,
								newsDetails.getId(), newsDetails.getSharelink(),
								details, newsDetails.hasGallery(),
								newsDetails.getGalleryUrlList(), title, language);
					}
				}
				catch (Exception e) {

				}
			}
		});

		nextNewsBtn = (Button) findViewById(R.id.nextNewsBtn);
		nextNewsBtn.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				if (!parent.equalsIgnoreCase("SavedNews")) {
					if (newsNo < newsList.size() - 1) {
						newsNo++;
						newNewsDetails();
					}
				} else {
					if (newsNo < newsDetailsVector.size() - 1) {
						newsNo++;
						newNewsDetails();
					}
				}
			}
		});
		if (parent.equalsIgnoreCase("SavedNews")) {
			showContentView();
		} else {
			try{
				if (!newsList.elementAt(newsNo).getNewsDetailsFlag()) {
					loadNewsDetails();
				} else {
					newsDetails = newsList.elementAt(newsNo).getNewsDetails();
					showContentView();
				}
			}
			catch (Exception e) {
			}
		}
	}

	private void newNewsDetails() {
		if (!parent.equalsIgnoreCase("SavedNews")) {
			newsId = newsList.elementAt(newsNo).getId();
			if (!newsList.elementAt(newsNo).getNewsDetailsFlag())
				loadNewsDetails();
			else {
				newsDetails = newsList.elementAt(newsNo).getNewsDetails();
				showContentView();
			}
		} else {
			newsDetails = newsDetailsVector.elementAt(newsNo);
			newsPaperId = newsDetails.getPaperId();
			newsId = newsDetails.getId();
			language = newsDetails.getLanguage();
			showContentView();
		}
		boolean isSaved = BanglaNews.getDatabaseManager().isNewsSaved(
				newsPaperId + newsId);
		if (isSaved) {
			saveNewsBtn.setText("Unsave");
		} else {
			saveNewsBtn.setText("Save News");
		}
	}

	private void loadNewsDetails() {
		try{
			if (BanglaNews.hashtable.containsKey(newsPaperId + newsId)) {
				newsDetails = BanglaNews.hashtable.get(newsPaperId + newsId);
				showContentView();
			} else {
				if (InternetConnectivity.isConnectedToInternet(this)) {
					progressDialog = ProgressDialog.show(this, null,
							"Loading. Please wait...", true, true);
					GetNewsDetails getNewsCategory = new GetNewsDetails();
					getNewsCategory.execute();
				} else {
					Toast toast = Toast.makeText(this,
							"Enable mobile network or Wi-Fi to download data",
							Toast.LENGTH_LONG);
					toast.show();
				}
			}			
		}
		catch (Exception e) {

		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		com.facebook.Settings.publishInstallAsync(this, MyApplication.fb_app_id);
	}

	@Override
	protected void onStart() {
		super.onStart();
		try {
			mGaTracker.sendView(String.format("/%s/NewsDetails/%s", newsPaperId, newsId));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	private class GetNewsDetails extends AsyncTask<Void, Void, Void> {
		@Override
		protected Void doInBackground(Void... params) {
			getNewsDetailsJson();
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			try{
				BanglaNews.hashtable.put(newsPaperId+newsId, newsDetails);			
				progressDialog.dismiss();
				progressDialog = null;
				if (!bError){
					showContentView();
				}
			}
			catch (Exception e) {
			}
		}
	}

	private void showContentView() {
		try{
			TextView title = (TextView) findViewById(R.id.title);
			TextView newsDetailsText = (TextView) findViewById(R.id.newsDetails);
			if (language.equals("bn")) {
				if (!parent.equalsIgnoreCase("SavedNews")) {
					title.setTypeface(fontBN);
					title.setText(ComplexScriptHelper.UnicodeToAnsi(newsDetails
							.getTitle()));
					newsDetailsText.setTypeface(fontBN);
					Spanned spnDetails = Html.fromHtml(ComplexScriptHelper
							.UnicodeToAnsi(newsDetails.getDetailsNews()));
					newsDetailsText.setText(spnDetails);
				} else {
					title.setTypeface(fontBN);
					title.setText(newsDetails.getTitle());
					newsDetailsText.setTypeface(fontBN);
					Spanned spnDetails = Html
							.fromHtml(newsDetails.getDetailsNews());
					newsDetailsText.setText(spnDetails);
				}
			} else {
				title.setTypeface(fontEN);
				title.setText(newsDetails.getTitle());
				newsDetailsText.setTypeface(fontEN);
				Spanned spnDetails = Html.fromHtml(newsDetails.getDetailsNews());
				newsDetailsText.setText(spnDetails);
			}

			FrameLayout galleryView = (FrameLayout) findViewById(R.id.gallery_in_newsdetails);
			
			//OLDIMAGE
			//ImageView imgNewsDetailsMain = (ImageView)findViewById(R.id.imgNewsDetailsMain);
			//--OLDIMAGE
			
			//NEWIMAGE
			SmartImageView news_details_image = (SmartImageView) this.findViewById(R.id.news_details_image);
			//--NEWIMAGE
			
			if (newsDetails.hasGallery()) {
				galleryView.setVisibility(View.VISIBLE);
				
				//OLDIMAGE
				//ImageLoader imageLoader = new ImageLoader(this);
				//imageLoader.DisplayImage(newsDetails.getGalleryUrlList().elementAt(0), 
				//		R.drawable.logo, 
				//		imgNewsDetailsMain, 
				//		true, null);
				//--OLDIMAGE
				
				//NEWIMAGE
				LayoutParams lp = null;
				if(BanglaNews.SCREEN_WIDTH < BanglaNews.SCREEN_HEIGHT){
					lp = new LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
							BanglaNews.SCREEN_WIDTH);	
				}
				else{
					lp = new LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
							BanglaNews.SCREEN_HEIGHT);
				}		
				lp.gravity = Gravity.CENTER;
				news_details_image.setLayoutParams(lp);
				news_details_image.setScaleType(ScaleType.CENTER_INSIDE);
				news_details_image.setImageUrl(newsDetails.getGalleryUrlList().elementAt(0));
				//--NEWIMAGE
				
				
				Button galleryBtn = (Button) findViewById(R.id.galleryBtn);
				galleryBtn.setOnClickListener(new OnClickListener() {

					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						Intent intent = new Intent(NewsDetailsActivity.this,
								GalleryActivity.class);
						startActivity(intent);
					}
				});
			} 
			else 
			{
				galleryView.setVisibility(View.GONE);
				//OLDIMAGE
				//if(imgNewsDetailsMain != null){
				//	imgNewsDetailsMain.setVisibility(View.GONE);
				//--OLDIMAGE
				
				//NEWIMAGE
				news_details_image.setVisibility(View.GONE);
				//--NEWIMAGE
			}			
		}
		catch (Exception e) {

		}
	}
	

	private void getNewsDetailsJson() {
		// TODO Auto-generated method stub
		String urlPath = BanglaNews.BASE_URL + "DDNGetNewsDetail" + "?id="
				+ newsPaperId + "&newsid=" + newsId+ "&appVersion="+MyApplication.app_version;
		try {
			String serverResonse = WebServerOperation.HTTPrequest(urlPath);
			parseNewsDetailsJSON(serverResonse);
		} catch (Exception e) {
			bError = true;
		}
	}

	private void parseNewsDetailsJSON(String serverResonse) throws Exception {
		// TODO Auto-generated method stub
		JSONObject jsonObject = new JSONObject(serverResonse);
		newsDetails = new NewsDetails();
		newsDetails.setId(jsonObject.getString("id"));
		newsDetails.setSharelink(jsonObject.getString("sharelink"));
		newsDetails.setDetailsNews(jsonObject.getString("details"));
		newsDetails.setTitle(newsList.elementAt(newsNo).getTitle());
		if (jsonObject.has("gallery")) {
			Vector<String> galleryUrlList = new Vector<String>();
			JSONArray jsonArray = jsonObject.getJSONArray("gallery");
			for (int i = 0; i < jsonArray.length(); i++) {
				galleryUrlList.add(jsonArray.getJSONObject(i).getString("url"));
			}
			newsDetails.setGalleryUrlList(galleryUrlList);
			newsDetails.setGalleryFlag(true);
		} else {
			newsDetails.setGalleryUrlList(null);
		}		
	}
}
